package com.huxiu;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.huxiu.utils.Constants;
import com.huxiu.utils.ImageUtils;
import com.huxiu.utils.Settings;
import com.huxiu.utils.UmenEvent;
import com.huxiu.utils.Utils;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.util.LogUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.sina.weibo.sdk.api.ImageObject;
import com.sina.weibo.sdk.api.TextObject;
import com.sina.weibo.sdk.api.WebpageObject;
import com.sina.weibo.sdk.api.WeiboMultiMessage;
import com.sina.weibo.sdk.api.share.BaseResponse;
import com.sina.weibo.sdk.api.share.IWeiboHandler;
import com.sina.weibo.sdk.api.share.IWeiboShareAPI;
import com.sina.weibo.sdk.api.share.SendMultiMessageToWeiboRequest;
import com.sina.weibo.sdk.api.share.WeiboShareSDK;
import com.sina.weibo.sdk.auth.AuthInfo;
import com.sina.weibo.sdk.auth.Oauth2AccessToken;
import com.sina.weibo.sdk.auth.WeiboAuthListener;
import com.sina.weibo.sdk.auth.sso.SsoHandler;
import com.sina.weibo.sdk.constant.WBConstants;
import com.sina.weibo.sdk.exception.WeiboException;
import com.sina.weibo.sdk.utils.Utility;
import com.tencent.connect.share.QQShare;
import com.tencent.connect.share.QzoneShare;
import com.tencent.mm.sdk.modelmsg.SendMessageToWX;
import com.tencent.mm.sdk.modelmsg.WXMediaMessage;
import com.tencent.mm.sdk.modelmsg.WXWebpageObject;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;
import com.umeng.analytics.MobclickAgent;

import java.util.ArrayList;

/**
 * Created by tian on 15/6/1:下午9:04.
 */
public class ShareActivity extends Activity
        implements View.OnClickListener, IWeiboHandler.Response, IUiListener {

    @ViewInject(R.id.share_qq)
    TextView shareQQ;

    @ViewInject(R.id.share_timeline)
    TextView shareTimeline;

    @ViewInject(R.id.share_weixin)
    TextView shareWeixin;

    @ViewInject(R.id.share_weibo)
    TextView shareWeibo;

    @ViewInject(R.id.copy_link)
    TextView copyLink;

    @ViewInject(R.id.share_qzone)
    TextView shareQzone;

    @ViewInject(R.id.cancel)
    ImageView cancel;

    @ViewInject(R.id.content)
    protected View content;

    @ViewInject(R.id.background)
    protected View background;

    private String title;

    private String link;

    private String type;

    private String imageUrl;

    private String description;

    private Bitmap image;

    private IWeiboShareAPI mWeiboApi;

    protected SsoHandler mSsoHandler;

    protected IWXAPI mWechatApi;

    private Tencent mTencent;

    private int SHARE_INTENT_VLAUE;

    private ShareActivity instance;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_share);
        ViewUtils.inject(ShareActivity.this);
        instance = this;
        background.setOnClickListener(this);
        cancel.setOnClickListener(this);
        shareQQ.setOnClickListener(this);
        shareTimeline.setOnClickListener(this);
        shareWeixin.setOnClickListener(this);
        shareWeibo.setOnClickListener(this);
        copyLink.setOnClickListener(this);
        shareQzone.setOnClickListener(this);
        title = getIntent().getStringExtra("title");
        link = getIntent().getStringExtra("url");
        type = getIntent().getStringExtra("type");
        image = getIntent().getParcelableExtra("image");
        imageUrl = getIntent().getStringExtra("imageUrl");
        description = getIntent().getStringExtra("description");
        SHARE_INTENT_VLAUE = getIntent().getIntExtra(UmenEvent.SHARE_INTENT_KEY, 0);
        mWechatApi = WXAPIFactory.createWXAPI(this, Constants.WECHAT_KEY);
        mTencent = Tencent.createInstance(Constants.TENCENT_APP_ID, getApplicationContext());
//        initWeiBo();
        mWeiboApi = WeiboShareSDK.createWeiboAPI(this, Constants.SinaAppKey);
        mWeiboApi.registerApp();
        mWeiboApi.handleWeiboResponse(getIntent(),ShareActivity.this);
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.cancel:
                finish();
                break;
            case R.id.background:
                finish();
                break;
            case R.id.share_weibo:
                switch (SHARE_INTENT_VLAUE) {
                    case UmenEvent.ARTICLE_SHARE:
                        UmenEvent.UmengEventMap(instance, UmenEvent.APP_ARTICLE_CONTENT, UmenEvent.ARTICLE_DETAIL_SHARE_WEIBO);
                        break;
                    case  UmenEvent.HUATI_SHARE:
                        UmenEvent.UmengEventMap(instance, UmenEvent.APP_TOPIC_LIST, UmenEvent.TOPIC_DETAIL_SHAREWEIBO);
                        break;
                    case UmenEvent.GROUP_SHARE:
                        UmenEvent.UmengEventMap(instance, UmenEvent.APP_TOPIC_DETAIL, UmenEvent.TOPIC_LIST_SHAREWEIBO);
                        break;
                }
                shareWeibo();
                finish();
                break;
            case R.id.share_weixin:
                Constants.WX_TYPE=Constants.WX_SHARE;
                switch (SHARE_INTENT_VLAUE) {
                    case UmenEvent.ARTICLE_SHARE:
                        UmenEvent.UmengEventMap(instance, UmenEvent.APP_ARTICLE_CONTENT, UmenEvent.ARTICLE_DETAIL_SHARE_WECHATFRIEND);
                        break;
                    case  UmenEvent.HUATI_SHARE:
                        UmenEvent.UmengEventMap(instance, UmenEvent.APP_TOPIC_LIST, UmenEvent.ARTICLE_DETAIL_SHARE_WECHATFRIEND);
                        break;
                    case UmenEvent.GROUP_SHARE:
                        UmenEvent.UmengEventMap(instance, UmenEvent.APP_TOPIC_DETAIL, UmenEvent.ARTICLE_DETAIL_SHARE_WECHATFRIEND);
                        break;
                }
                shareWeChatFriends();
                finish();
                break;
            case R.id.share_timeline:
                Constants.WX_TYPE=Constants.WX_SHARE;
                switch (SHARE_INTENT_VLAUE) {
                    case UmenEvent.ARTICLE_SHARE:
                        UmenEvent.UmengEventMap(instance, UmenEvent.APP_ARTICLE_CONTENT, UmenEvent.ARTICLE_DETAIL_SHARE_WECHATTIMELINE);
                        break;
                    case  UmenEvent.HUATI_SHARE:
                        UmenEvent.UmengEventMap(instance, UmenEvent.APP_TOPIC_LIST, UmenEvent.ARTICLE_DETAIL_SHARE_WECHATTIMELINE);
                        break;
                    case UmenEvent.GROUP_SHARE:
                        UmenEvent.UmengEventMap(instance, UmenEvent.APP_TOPIC_DETAIL, UmenEvent.ARTICLE_DETAIL_SHARE_WECHATTIMELINE);
                        break;
                }
                shareWeChatTimeline();
                finish();
                break;
            case R.id.share_qq:
                shareQQ();
                finish();
                break;
            case R.id.share_qzone:
                shareQzone();
                finish();
                break;
            case R.id.copy_link:
                Utils.doCopy(link);
                Utils.showToast(R.string.copied);
                finish();
                break;
        }
    }

    private void shareQQ() {
        Bundle b = new Bundle();
        b.putString(QQShare.SHARE_TO_QQ_TITLE, title);
        if (!TextUtils.isEmpty(description)) {
            String s = description;
            if (s.length() > 40) {
                s = description.substring(0, 40);
            }
            b.putString(QQShare.SHARE_TO_QQ_SUMMARY, s);
        }
        if (!TextUtils.isEmpty(imageUrl)) {
            b.putString(QQShare.SHARE_TO_QQ_IMAGE_URL, imageUrl);
        }
        if (!TextUtils.isEmpty(link)) {
            b.putString(QQShare.SHARE_TO_QQ_TARGET_URL, link);
        }
        b.putString(QQShare.SHARE_TO_QQ_APP_NAME, getString(R.string.app_name));
        b.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE, QQShare.SHARE_TO_QQ_TYPE_DEFAULT);
        b.putInt(QQShare.SHARE_TO_QQ_EXT_INT, QQShare.SHARE_TO_QQ_FLAG_QZONE_ITEM_HIDE);
        mTencent.shareToQQ(this, b, this);
    }

    private void shareQzone() {
        Bundle b = new Bundle();
        b.putString(QzoneShare.SHARE_TO_QQ_TITLE, title);
        if (!TextUtils.isEmpty(description)) {
            String s = description;
            if (s.length() > 40) {
                s = description.substring(0, 40);
            }
            b.putString(QzoneShare.SHARE_TO_QQ_SUMMARY, s);
        }
        if (!TextUtils.isEmpty(imageUrl)) {
            ArrayList<String> list = new ArrayList<>();
            list.add(imageUrl);
            b.putStringArrayList(QzoneShare.SHARE_TO_QQ_IMAGE_URL, list);
        }
        if (!TextUtils.isEmpty(link)) {
            b.putString(QzoneShare.SHARE_TO_QQ_TARGET_URL, link);
        }
        b.putString(QzoneShare.SHARE_TO_QQ_APP_NAME, getString(R.string.app_name));
        b.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE, QzoneShare.SHARE_TO_QZONE_TYPE_IMAGE_TEXT);

        mTencent.shareToQzone(this, b, this);
    }

    protected void shareWeChatTimeline() {
        shareWeChat(mWechatApi, link, title, description, ImageUtils.getWeChatShareBitmap(image),
                true);
    }

    protected void shareWeChatFriends() {
        shareWeChat(mWechatApi, link, title, description, ImageUtils.getWeChatShareBitmap(image),
                false);
    }


    private void shareWeChat(IWXAPI wechatApi, String url, String title,
                             String description, Bitmap bitmap, boolean isTimeline) {
        if (!wechatApi.isWXAppInstalled()) {
            Toast.makeText(this, R.string.wechat_not_installed, Toast.LENGTH_SHORT)
                    .show();
            return;
        } else if (!wechatApi.isWXAppSupportAPI()) {
            Toast.makeText(this, R.string.wechat_not_supported, Toast.LENGTH_SHORT)
                    .show();
            return;
        }
        WXWebpageObject webpage = new WXWebpageObject();
        webpage.webpageUrl = url;
        WXMediaMessage msg = new WXMediaMessage(webpage);
        msg.title = title;
        if (description != null) {
            msg.description = description;
        }
        msg.setThumbImage(bitmap);
        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = "webpage" + +System.currentTimeMillis();
        req.message = msg;
        req.scene = isTimeline ? SendMessageToWX.Req.WXSceneTimeline
                : SendMessageToWX.Req.WXSceneSession;
        boolean b = wechatApi.sendReq(req);
    }

    protected void shareWeibo() {
        mWeiboApi = WeiboShareSDK.createWeiboAPI(this, Constants.SinaAppKey);
        mWeiboApi.registerApp();
        if (!mWeiboApi.isWeiboAppInstalled()) {
            Utils.showToast(R.string.weibo_not_installed);
            return;
        }
        WeiboMultiMessage multmess = new WeiboMultiMessage();
        WebpageObject mediaObject = new WebpageObject();

        mediaObject.identify = Utility.generateGUID();
        mediaObject.title = title;
        mediaObject.description = description;

        Bitmap bmp =image;
        mediaObject.setThumbImage(bmp);
        ImageObject object = new ImageObject();
        object.setImageObject(bmp);
        mediaObject.actionUrl = link;
        mediaObject.defaultText = "";
        multmess.imageObject = object;
        multmess.mediaObject = mediaObject;
        SendMultiMessageToWeiboRequest multRequest = new SendMultiMessageToWeiboRequest();
        multRequest.multiMessage = multmess;
        multRequest.transaction = String.valueOf(System.currentTimeMillis());
        mWeiboApi.sendRequest(this, multRequest);
    }

    protected void initWeiBo() {
        AuthInfo weiboAuth = new AuthInfo(this, Constants.SinaAppKey,
                Constants.SinaAppRedirectURI, Constants.SinaScope);
        mSsoHandler = new SsoHandler(this, weiboAuth);
//        mSsoHandler.authorize(this);
    }


    /**
     * @see {@link Activity#onNewIntent}
     */
    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        // 从当前应用唤起微博并进行分享后，返回到当前应用时，需要在此处调用该函数
        // 来接收微博客户端返回的数据；执行成功，返回 true，并调用
        // {@link IWeiboHandler.Response#onResponse}；失败返回 false，不调用上述回调
        mWeiboApi.handleWeiboResponse(intent, this);
    }

    @Override
    public void onResponse(BaseResponse baseResponse) {
        Log.e("baseResponse","baseResponse"+baseResponse);
        switch (baseResponse.errCode) {


            case WBConstants.ErrorCode.ERR_OK:
                Toast.makeText(this, R.string.weibo_share_success, Toast.LENGTH_LONG)
                        .show();
                finish();
                break;
            case WBConstants.ErrorCode.ERR_CANCEL:
                Toast.makeText(this, R.string.weibo_share_cancel, Toast.LENGTH_LONG)
                        .show();
                break;
            case WBConstants.ErrorCode.ERR_FAIL:
                Toast.makeText(this,
                        getString(R.string.weibo_share_failed) + ": " + baseResponse.errMsg,
                        Toast.LENGTH_LONG).show();
                break;
        }
    }

//    @Override
//    public void onComplete(Bundle bundle) {
//        Oauth2AccessToken weiboToken = Oauth2AccessToken.parseAccessToken(bundle);
//        Settings.saveWeiboAccessToken(weiboToken);
//        Log.e("weibo","onComplete");
////        finish();
//
//    }

//    @Override
//    public void onWeiboException(WeiboException e) {
//        Log.e("weibo", "onWeiboException");
////        finish();
//    }

    @Override
    public void onComplete(Object o) {
        Toast.makeText(this,"分享成功",
                Toast.LENGTH_SHORT
        )
                .show();
        Log.e("weibo", "onComplete");
    }

    @Override
    public void onError(UiError uiError) {
        LogUtils.d("QQ Log In failed: " + uiError.errorDetail + ", " + uiError.errorMessage);

        Log.e("weibo", "onComponErrorlete");
        finish();

    }

    @Override
    public void onCancel() {
        Log.e("weibo", "onCancel");
        finish();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (mSsoHandler != null) {
            mSsoHandler.authorizeCallBack(requestCode, resultCode, data);
        }
    }

//    @Override
//    public void finish() {
//        background.setBackgroundColor(getResources().getColor(android.R.color.transparent));
//        super.finish();
//        overridePendingTransition(R.anim.push_in_from_bottom, R.anim.push_out_to_bottom);
//    }

    @Override
    protected void onStart() {
        super.onStart();
        Animation animation = AnimationUtils.loadAnimation(this, R.anim.push_in_from_bottom);
        content.startAnimation(animation);
        AlphaAnimation animation1 = new AlphaAnimation(0.0f, 1.0f);
        animation1.setDuration(200);
        animation1.setFillAfter(true);
        background.startAnimation(animation1);
    }


//    @Override
//    public void finish() {
//        // TODO Auto-generated method stub
//        super.finish();
//        //关闭窗体动画显示
//        this.overridePendingTransition(R.anim.activity_colse, 0);
//    }


    @Override
    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart("SplashScreen");
        MobclickAgent.onResume(this);
    }

    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd("SplashScreen");
        MobclickAgent.onPause(this);
    }

}
